package com.sangeng.service.impl;

import com.alibaba.fastjson.JSON;
import com.sangeng.domain.LoginUser;
import com.sangeng.domain.User;
import com.sangeng.domain.response.RespBean;
import com.sangeng.mapper.MockRedisMapper;
import com.sangeng.service.LoginService;
import com.sangeng.service.MockRedisService;
import com.sangeng.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MockRedisService mockRedisService;

    @Override
    public RespBean login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 使用useId 生成token
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //将 authenticate 存入redis
        int i = mockRedisService.set("login:" + userId, JSON.toJSONString(loginUser), 300L);
        if (i>0){
            HashMap<String, String> map = new HashMap<>();
            map.put("token",jwt);
            return new RespBean(200,"登录成功",map);
        }
        return RespBean.error("登录失败");

    }

    @Override
    public RespBean logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        int i = mockRedisService.delete("login:" + id.toString());
        return RespBean.success("退出成功");
    }
}
